package com.mojo.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.Map;

/**
 * 事务实现-编程式事务(TransactionTemplate)
 *
 * @author <a href="mailto:sjj@jianzhimao.com">mojo</a>
 * copyright (C), 2013-2022, 广州九尾信息科技有限公司
 * @date 2022/3/4 14:17
 */
@Repository
public class UserDaoImpl_Template implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private TransactionTemplate tt;


    @Override
    public int update(Long id) {
        Object execute = tt.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus status) {

                int update = 0;
                try {
                    String sql = "update backstage_user set nickname= ? where id=?";
                    Object[] objects = {"一只牧哲1", 1};
                    update = jdbcTemplate.update(sql, objects);
                    List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from backstage_user where id=1");
                    for (Map<String, Object> map : maps) {
                        System.out.println(map);
                    }
                    String insert = "insert into backstage_role (name,description) values(?,?)";
                    Object[] objects1 = {"超管22"};
                    int insert1 = jdbcTemplate.update(insert, objects1);
                } catch (DataAccessException | TransactionException e) {
                    e.printStackTrace();
                    status.setRollbackOnly();
                    System.out.println(">>>>>>>>>>事务异常");
                }

                return update;
            }
        });
        return 0;
    }
}